﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyWeb.ServiceBus.Extensions.Authentication;
using MyWeb.ServiceBus.Extensions.Consul;
using MyWeb.ServiceBus.Extensions.Db;
using MyWeb.ServiceBus.Extensions.Nacos;
using MyWeb.ServiceBus.Extensions.Serialization;
using MyWeb.ServiceBus.Extensions.Swagger;
using MyWeb.ServiceBus.Services;
using MyWeb.ServiceBus.Services.Impl;

namespace MyWeb.ServiceBus.Extensions
{
    /// <summary>
    /// 项目启动服务
    /// </summary>
    public static class ProgramSetup
    {
        /// <summary>
        /// Extensions 启动服务
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddProgramSetup(this IServiceCollection services, IConfigurationRoot? config)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            //json格式序列化规则
            services.AddSerializationFormatSetup();
            services.AddSwaggerSetup();
            //services.AddJwtAuthSetup();
            services.AddIdsAuthSetup();

            services.AddEFDbContextSetup();

            // 配置跨域处理，允许所有来源
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolocy", p =>
                {
                    p.AllowAnyOrigin()//允许所有Origin策略
                    .AllowAnyMethod()//允许所有请求方法：get,post.put,delete
                    .AllowAnyHeader();//允许所有请求头：application/json
                    //.WithExposedHeaders("Authorization") // 允许暴露 Authorization 头部;
                    //.AllowCredentials();
                });
            });
            var isConsul = config.GetValue<bool>("Consul:enable");
            if (isConsul) { services.AddConsul(config); }

            var isNacos = config.GetValue<bool>("Nacos:enable");
            if (isNacos) { services.AddNacosSetup(config); }

            services.AddHttpContextAccessor();
            services.AddScoped<IOperatorProvider,OperatorProvider>();
        }
    }
}